// TTS语音合成前端JavaScript代码

let currentController = null; // 当前的AbortController
let currentRequestId = null; // 当前的请求ID
let activeRequests = []; // 活跃请求列表

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    // 初始化分段TTS功能
    initSegmentTTS();
    
    // 定期刷新活跃请求列表
    setInterval(refreshActiveRequests, 2000);
});

// 开始TTS转换
async function startTTS() {
    const text = document.getElementById('ttsText').value.trim();
    if (!text) {
        showStatus('请输入要转换的文本', 'error');
        return;
    }

    // 禁用按钮
    document.getElementById('startTTS').disabled = true;
    document.getElementById('cancelTTS').disabled = false;
    showStatus('正在转换中...', 'loading');

    // 创建新的AbortController
    currentController = new AbortController();
    const signal = currentController.signal;

    try {
        const response = await fetch('/api/tts', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ text: text }),
            signal: signal
        });

        if (!response.ok) {
            const errorData = await response.json();
            throw new Error(errorData.error || '请求失败');
        }

        // 获取音频数据
        const audioBlob = await response.blob();
        const audioUrl = URL.createObjectURL(audioBlob);
        
        // 显示音频播放器
        const audioPlayer = document.getElementById('audioPlayer');
        const audioContainer = document.getElementById('audioContainer');
        
        audioPlayer.src = audioUrl;
        audioContainer.style.display = 'block';
        
        showStatus('转换完成！', 'success');
        
        // 自动播放
        audioPlayer.play().catch(e => {
            console.log('自动播放被阻止:', e);
        });

    } catch (error) {
        if (error.name === 'AbortError') {
            showStatus('转换已取消', 'error');
        } else {
            showStatus('转换失败: ' + error.message, 'error');
        }
    } finally {
        // 恢复按钮状态
        document.getElementById('startTTS').disabled = false;
        document.getElementById('cancelTTS').disabled = true;
        currentController = null;
    }
}

// 取消TTS转换
function cancelTTS() {
    if (currentController) {
        currentController.abort();
        currentController = null;
    }
}

// 显示状态信息
function showStatus(message, type) {
    const statusDiv = document.getElementById('ttsStatus');
    statusDiv.textContent = message;
    statusDiv.className = 'status ' + type;
    statusDiv.style.display = 'block';
    
    // 3秒后隐藏成功消息
    if (type === 'success') {
        setTimeout(() => {
            statusDiv.style.display = 'none';
        }, 3000);
    }
}

// 浏览器原生TTS功能
function startNativeTTS() {
    const text = document.getElementById('nativeText').value.trim();
    if (!text) {
        alert('请输入要朗读的文本');
        return;
    }

    // 检查浏览器是否支持Web Speech API
    if ("speechSynthesis" in window) {
        // 停止之前的朗读
        window.speechSynthesis.cancel();
        
        // 创建新的语音合成实例
        const utterance = new SpeechSynthesisUtterance(text);
        
        // 设置语音属性
        utterance.lang = 'zh-CN';
        utterance.rate = 1; // 语速
        utterance.pitch = 1; // 音调
        utterance.volume = 1; // 音量
        
        // 启动语音合成
        window.speechSynthesis.speak(utterance);
    } else {
        alert("抱歉，您的浏览器不支持语音合成功能");
    }
}

// 停止浏览器原生TTS
function stopNativeTTS() {
    if ("speechSynthesis" in window) {
        window.speechSynthesis.cancel();
    }
}

// 初始化分段TTS功能
function initSegmentTTS() {
    const segments = document.querySelectorAll('.segment');
    
    segments.forEach((segment) => {
        segment.addEventListener('mouseenter', () => {
            const text = segment.dataset.segment;
            
            // 如果有未完成的请求，取消它
            if (currentController) {
                currentController.abort();
            }
            
            // 高亮当前段落
            segments.forEach(s => s.classList.remove('active'));
            segment.classList.add('active');
            
            // 创建新的AbortController
            currentController = new AbortController();
            const signal = currentController.signal;
            
            // 发起TTS请求
            fetchTTS(text, signal)
                .then((audioUrl) => {
                    // 创建临时音频元素播放
                    const audio = new Audio(audioUrl);
                    audio.play().catch(e => {
                        console.log('播放失败:', e);
                    });
                })
                .catch((error) => {
                    if (error.name === "AbortError") {
                        console.log(`TTS请求被取消: ${text}`);
                    } else {
                        console.error(`TTS请求失败: ${text}`, error);
                    }
                });
        });
        
        segment.addEventListener('mouseleave', () => {
            segment.classList.remove('active');
        });
    });
}

// 分段TTS请求函数
async function fetchTTS(text, signal) {
    try {
        const response = await fetch('/api/tts', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ text: text }),
            signal: signal
        });

        if (!response.ok) {
            const errorData = await response.json();
            throw new Error(errorData.error || '请求失败');
        }

        const audioBlob = await response.blob();
        return URL.createObjectURL(audioBlob);
    } catch (error) {
        throw error;
    }
}

// 刷新活跃请求列表
async function refreshActiveRequests() {
    try {
        const response = await fetch('/api/tts/active');
        const data = await response.json();
        
        const container = document.getElementById('activeRequests');
        
        if (data.activeRequests.length === 0) {
            container.innerHTML = '<p>暂无活跃请求</p>';
            return;
        }
        
        container.innerHTML = data.activeRequests.map(request => `
            <div class="request-item">
                <div class="request-info">
                    <div class="request-id">请求ID: ${request.requestId}</div>
                    <div class="request-duration">运行时间: ${Math.round(request.duration / 1000)}秒</div>
                </div>
                <button onclick="cancelRequest('${request.requestId}')" class="danger">取消</button>
            </div>
        `).join('');
        
    } catch (error) {
        console.error('获取活跃请求失败:', error);
    }
}

// 取消指定请求
async function cancelRequest(requestId) {
    try {
        const response = await fetch(`/api/tts/${requestId}`, {
            method: 'DELETE'
        });
        
        if (response.ok) {
            alert('请求已取消');
            refreshActiveRequests();
        } else {
            const errorData = await response.json();
            alert('取消失败: ' + errorData.error);
        }
    } catch (error) {
        alert('取消失败: ' + error.message);
    }
}
